
#include<stdlib.h>
#include<pthread.h>
#include<cstring>
#include"thread_list.h"
#include<proto.h>
#include<syslog.h>
#include<arpa/inet.h>
#include"server_config.h"
#include<unistd.h>

static pthread_t tid_list;
static int nr_list_ent;
static media_entity_st * list_ent;

void * thr_list(void *p){
    int totalsize,ret;
    msg_list_st* ent_list_p;
    msg_list_entity_st * entity_p;
    totalsize = sizeof(channid_t);
    for(int i=0;i<nr_list_ent;i++){
        totalsize+= sizeof(msg_list_entity_st)-1+strlen(list_ent[i].desc);
    }
    ent_list_p =(msg_list_st*) malloc(totalsize);

    if(ent_list_p==NULL){
        syslog(LOG_ERR,"malloc failed");
        exit(0);
    }
    ent_list_p->channid = LISTCHANN;
    entity_p = ent_list_p->entity;
    int size=0;
    for(int i=0;i<nr_list_ent;i++){
        size = sizeof(msg_list_entity_st)-1+strlen(list_ent[i].desc);
        entity_p->channid = list_ent[i].channid;
        entity_p->data_len = htons(size);
        strcpy(entity_p->desc,list_ent[i].desc);
        entity_p = (msg_list_entity_st*)((char*)entity_p+size);
    }
    while(1){
        ret = sendto(server_fd,ent_list_p,totalsize,0,(sockaddr*)&sendaddr,sizeof(sendaddr));

        if(ret<0){
            syslog(LOG_WARNING,"send error");
        }else{
            syslog(LOG_DEBUG,"send %d bytes succes in [ %s :  %d ]",ret,__FILE__,__LINE__);
        }
        usleep(1000000);
    }
}

int thr_list_create(media_entity_st* list_p,int nr_ent){
    int err;
    list_ent = list_p;
    nr_list_ent = nr_ent;
    err = pthread_create(&tid_list,NULL,thr_list,NULL);
    if(err){
        syslog(LOG_ERR,"pthread_create list failed");
        return -1;
    }
    return 0;
}
int thr_list_destory(void){
    pthread_cancel(tid_list);
    pthread_join(tid_list,NULL);
    return 0;
}